//
//  MeVC.swift
//  whale
//
//  Created by topnet on 2022/7/1.
//

import UIKit

class MeVC: BaseView {

    var dataSource: [MeModel]?
    var iapModel: IAPModel = .init()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        listV.tableHeaderView = MeHeaderView()
       
        view.addSubview(listV)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let termsVC = storyboard.instantiateViewController(withIdentifier: "TermsView")
        
        let privacyVC = storyboard.instantiateViewController(withIdentifier: "PrivacyView")
        
        dataSource = [
            MeModel(rows: [
                ViewItemModel(name: "隐私协议", icon: nil, vc: privacyVC),
                ViewItemModel(name: "许可协议", icon: nil, vc: termsVC),
            ]),
            MeModel(headerHeight: 10.adapter, rows: [
                ViewItemModel(name: "选择服务器", icon: nil, vc: getServers()),
                ViewItemModel(name: "恢复购买", icon: nil, vc: nil),
                ViewItemModel(name: "设置", icon: nil, vcType: SetVC.self),
            ]),
        ]
        listV.configData(data: dataSource, cellType: MeCell.self) {  path, md, cell in
            
        } itemSelected: { [weak self] path, md in
            LogUtil.log(path)
            if let mod = md as? ViewItemModel {
                if let vcType = mod.vcType {
                    self?.push(type: vcType)
                }
                if let vc = mod.vc {
                    self?.push(vc)
                }
                if path.section == 1 && path.row == 1 {
                    self?.profileAccountCellTapRestore()
                }
            }
        }
        NotificationCenter.default.addObserver(self, selector: #selector(iapStateNoti), name: NSNotification.Name.init("iap"), object: nil)
    }
    
    @objc private func iapStateNoti() {
        listV.reloadData()
    }
    
    func getServers() -> UIViewController? {
        let listVPNServerView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ListVPNServerView") as! ListVPNServerView
        listVPNServerView.delegate = self
        if let data = UserDefaults.standard.data(forKey: "server"),
           let server = Server(data: data){
            listVPNServerView.serverSelected = server
        }
        return listVPNServerView
    }
    
    func profileAccountCellTapRestore() {
        self.iapModel = IAPModel()
        self.iapModel.loading.bind(to: self.rx.isAnimating).disposed(by: self.dispose)
        self.iapModel.error.bind(to: self.rx.isError).disposed(by: self.dispose)
        self.iapModel.specialError.subscribe { (error) in
            self.show(msg: error.localizedDescription) { (a, b, i) in
                if i > 0 {
                    self.tabBarController?.selectedIndex = 1
                }
            }
        } onCompleted: {
            
        }.disposed(by: self.dispose)
        self.iapModel.productRestore.subscribe { (purchaseDetail) in
            self.listV.reloadData()
            (self.listV.tableHeaderView as? MeHeaderView)?.updateData()
        } onCompleted: {
            
        }.disposed(by: self.dispose)
        
        self.iapModel.restore()
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        listV.left_right(view).top(0).bottom(view.bounds.height-view.safeAreaInsets.bottom)
    }
    

    
    lazy var listV: GroupedListView = {
        let v = GroupedListView(frame: .zero, style: .grouped)
        v.cellType = MeCell.self
        v.backgroundColor = .background
        return v
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}


extension MeVC: ListVPNServerViewProtocol {
    func listVPNDidTapServer(server: Server) {
        let mod = dataSource?.last?.rows?.first as! ViewItemModel
        mod.name = server.country
        mod.content = server.countryCode
    
        UserDefaults.standard.setValue(server.encode(), forKey: "server")
        UserDefaults.standard.synchronize()
        
        listV.reloadData()
    }
}

extension MeVC {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let data = UserDefaults.standard.value(forKey: "server") as? Data else {
            reloadData()
            return }
        let server = Server(data: data)
        let mod = dataSource?.last?.rows?.first as! ViewItemModel
        mod.name = server?.country
        mod.content = server?.countryCode
        
        reloadData()
    }
    
    func reloadData() {
        
        listV.reloadData()
        
        (listV.tableHeaderView as? MeHeaderView)?.updateData()
    }
}
